<?php
    
    define('CACHEDIR', dirname(__FILE__).'/cache/');
    
    include('functions.php');
    
    $page = isset($_GET['page'])?abs(intval($_GET['page'])):1;
    
    $json = curl("http://www.djmaxcn.com/ranking/GetRankCrew.asp?p={$page}");
    
    $rank = json_decode($json);
    
    if($rank->DATA->ROW === 0) exit('发生错误, 请返回!');
    
//    $recodes = $rank->DATA->RECORD;
    
    $cookieName = 'crewrankid';
    $rankCache = array();
    if(isset($_COOKIE[$cookieName])) {
        $rankCache = readCache($_COOKIE[$cookieName]);
    } else {
        foreach($rank->DATA->RECORD as $recode) {
            $rankCache[$recode->CREWNAME] = $recode->CREWPOINT;
        }
        $timestamp = time();
        writeCache($timestamp, $rankCache);
        setcookie($cookieName, $timestamp);
    }

    getHead('战队排名');

    echo '<table><tr><th>排名</th><th>队名</th><th>分数</th><th>增量</th></tr>';
    foreach($rank->DATA->RECORD as $recode) {
        if( isset($rankCache[$recode->CREWNAME]) &&
                $recode->CREWPOINT - $rankCache[$recode->CREWNAME]>0 ) {
            $increment = $recode->CREWPOINT - $rankCache[$recode->CREWNAME];
            $increment = " +{$increment}EXP ";
        } else {
            $increment = ' --- ';
        }
        echo "<tr><td>{$recode->RANK}</td><td>{$recode->CREWNAME}</td><td>{$recode->CREWPOINT}</td><td align=\"center\">{$increment}</td></tr>";
    }
    echo '</table>';
    
    $link = '<a href="?page={$page}">{$name}</a>  ';
    
    echo "<h4>第{$rank->DATA->PAGE}页, 每页{$rank->DATA->PAGESIZE}项</h4>";
    
    $prev = '';
    if($page>1) {
        $prev = str_replace('{$page}', $page-1, $link);
        $prev = str_replace('{$name}', '上一页', $prev);
    }
    
    $next = str_replace('{$page}', $page+1, $link);
    $next = str_replace('{$name}', '下一页', $next);
    
    echo "<p style=\"text-align: center;\">{$prev}&#160;&#160;&#160;{$next}</p>";
    
    getFoot();
?>